package cat.joronya.supermanager.service;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.SupermanagerActivity;

/**
 * Update all content one by one calling each parser.
 * @author pol
 *
 */
public class FullContentUpdater 
{
	private static final String TAG = "supermanager";
	private SupermanagerService service;
	private DefaultHttpClient client;
	private Integer jornada;
	private Integer nextJornada;
	private int status;
	private boolean showNotifications;
	
	public FullContentUpdater(SupermanagerService theService, DefaultHttpClient theClient, 
			Integer theJornada, Integer theNextJornada, int theStatus, boolean theShowNotifications )
	{
		Log.d(TAG, "FullContentUpdater: initializing content updater");
		
		// registrem el context
		this.service = theService;
		this.client = theClient;
		this.jornada = theJornada;
		this.nextJornada = theNextJornada;
		this.status = theStatus;
		this.showNotifications = theShowNotifications;
	}
	
	/**
	 * Start update of content.
	 */
	public void update()
	{
		Log.d(TAG, "FullContentUpdater: starting content updater");
		
		Log.d(TAG, "FullContentUpdater: show notifications? "+(showNotifications?"true":"false"));
		
		// mostrem una notification
		showNotification(service.getString(R.string.update_started_notification_title),
				service.getString(R.string.update_started_notification_text), 
				service.getString(R.string.update_started_notification_ticker));
		
		// market
		Log.d(TAG, "FullContentUpdater: starting market content updater");
		
		// per defecte actualitzem amb jornada actual
		Integer day = jornada;
		// si estan canvis oberts, actualitzem amb next jornada
		if( status == Supermanager.OPEN_STATUS )
			day = nextJornada;
		
		// parse day matches
		DayMatchesSync dayMatchesSync = new DayMatchesSync(client, day);
		dayMatchesSync.sync();
		
		// parse next matches
		NextMatchesSync nextMatchesSync = new NextMatchesSync(service, client);
		nextMatchesSync.sync();
		
		// sync, internament fa 3 peticions i persisteix resultats
		MarketSync marketSync = new MarketSync(service, client, day);
		marketSync.setDayMatches(dayMatchesSync.getDayMatches());
		marketSync.sync();
		
		if( marketSync.status == Supermanager.CONNECTIVITY_ERROR_STATUS )
		{
			showNotification(service.getString(R.string.update_conn_error_notification_title),
					service.getString(R.string.update_conn_error_notification_text), 
					service.getString(R.string.update_conn_error_notification_ticker));
			return;
		}
		else if( marketSync.status == Supermanager.CLOSED_STATUS )
		{
			showNotification(service.getString(R.string.update_closed_error_notification_title),
					service.getString(R.string.update_closed_error_notification_text), 
					service.getString(R.string.update_closed_error_notification_ticker));
			// en cas de canvis tancats podem continuar parsejant
		}
		else if( marketSync.status == Supermanager.OTHER_ERROR_STATUS )
		{
			showNotification(service.getString(R.string.update_unknown_error_notification_title),
					service.getString(R.string.update_unknown_error_notification_text), 
					service.getString(R.string.update_unknown_error_notification_ticker));
			return;
		}
		
		// market
		Log.d(TAG, "FullContentUpdater: starting my teams content updater");
		
		// per defecte actualitzem amb jornada actual
		day = nextJornada;
		
		// get my teams
		MyTeamsSync myTeamsSync = new MyTeamsSync(service, client, day);
		// si no hi ha error guardem a db
		myTeamsSync.setDayMatches(dayMatchesSync.getDayMatches());
		myTeamsSync.sync();
		
		switch(myTeamsSync.status)
		{
			case Supermanager.CONNECTIVITY_ERROR_STATUS:
				showNotification(service.getString(R.string.update_conn_error_notification_title),
						service.getString(R.string.update_conn_error_notification_text), 
						service.getString(R.string.update_conn_error_notification_ticker));
				return;
			case Supermanager.OTHER_ERROR_STATUS:
				showNotification(service.getString(R.string.update_unknown_error_notification_title),
						service.getString(R.string.update_unknown_error_notification_text), 
						service.getString(R.string.update_unknown_error_notification_ticker));
				return;
		}
		
		// market
		Log.d(TAG, "FullContentUpdater: starting private leagues content updater");
		
		// get private leagues
		PrivateLeaguesSync plSync = new PrivateLeaguesSync(service, client);
		// parsejem i si no hi ha error guardem a db
		plSync.sync();
		
		switch(plSync.status)
		{
			case Supermanager.CONNECTIVITY_ERROR_STATUS:
				showNotification(service.getString(R.string.update_conn_error_notification_title),
						service.getString(R.string.update_conn_error_notification_text), 
						service.getString(R.string.update_conn_error_notification_ticker));
				return;
			case Supermanager.OTHER_ERROR_STATUS:
				showNotification(service.getString(R.string.update_unknown_error_notification_title),
						service.getString(R.string.update_unknown_error_notification_text), 
						service.getString(R.string.update_unknown_error_notification_ticker));
				return;
		}
		
		// tot updatat, tot ok: ho notifiquem
		showNotification(service.getString(R.string.update_success_notification_title),
				service.getString(R.string.update_success_notification_text), 
				service.getString(R.string.update_success_notification_ticker));
	}
	
	protected void showNotification(String title, String text, String ticker)
	{
		// si no ens han demanat notificacions, tornem
		if( !showNotifications )
			return;
		
		// get notification manager
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = 
			(NotificationManager) service.getSystemService(ns);
		
		// per quan creem notification
		long when = System.currentTimeMillis();

		// creem notification
		Notification notification = 
			new Notification(R.drawable.ic_stat_notification, ticker, when);
		
		// auto cancel flag added
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		// add sound notification
		notification.defaults |= Notification.DEFAULT_SOUND;
		
		// creem activity a llançar quan cliquem sobre la notification
		Intent notificationIntent = new Intent(service, SupermanagerActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(service, 0, notificationIntent, 0);

		// registrem el pending intent
		notification.setLatestEventInfo(service, title, text, contentIntent);
		
		// llancem notification
		mNotificationManager.notify(0, notification);
	}

}
